package cn.infinite.security.handler;

import cn.infinite.security.configuration.WxConfigurerProperties;
import cn.infinite.security.util.HttpProtocolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class DefaultWxAuthenticationSuccessHandler implements WxAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private WxConfigurerProperties wxConfigurerProperties;

    public DefaultWxAuthenticationSuccessHandler(WxConfigurerProperties wxConfigurerProperties) {
        this.wxConfigurerProperties = wxConfigurerProperties;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
            authentication) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            log.info("wx authenticate success, redirect to saved request url =>{}", savedRequest.getRedirectUrl());
        }
        String redirectUrl = savedRequest != null ? HttpProtocolUtil.parseToHttps(savedRequest.getRedirectUrl())
                : this.wxConfigurerProperties.getAuthenticateSuccessUrl();
        log.info("wx authenticate success, guide user to page =>{}", redirectUrl);
        this.redirectStrategy.sendRedirect(request, response, redirectUrl);
    }

}
